<template>
  <div>
    <div class="g6 mb20">
      <span>提示：回调函数会根据不同组件的回调内置不同的参数</span>
    </div>
    <div class="ks-row-middle mb20 lh1">
      <div class="mr10">参数</div>
      <i
        class="el-icon-circle-plus-outline iconcolor f20 poi"
        @click="addEventParam"
      ></i>
    </div>

    <div
      class=" pr15 ell item"
      v-for="(param, index) in paramList"
      :key="index"
    >
      <div
        :key="index"
        style="min-height: 32px"
        class="ks-row-middle-between mb10">
        <span class="ell">{{ param.value }}</span>
        <span v-if="param.editable" class="g6">
          <el-button type="text" style="margin-right: 10px" @click="editEventParam(param.value, index)">
            <i class="el-icon-edit"></i>
          </el-button>
          <span
            class="iconfont iconicon_shanchu poi"
            @click="removeParams(param, index)"
          ></span>
        </span>

      </div>
    </div>
    <div>
    </div>
    <addParam ref="addParam" @addParam="handleAddParam" @editParam="handleEditParam"/>
  </div>
</template>

<script>
import Blockly from 'blockly'
import addParam from '../addParam'
import EventBus from '@/utils/eventBus'
export default {
  name: 'CallbackFunctionExpression',
  props: {
    eventItem: {}, // 需要逻辑编排的对象
    componentItem: {},
    block: {},
    workspace: {}
  },
  components: { addParam },
  data () {
    return {
      formData: {},
      paramList: [],
      modalOpenFlag: false, // 打开弹窗成功回调
      modalCloseFlag: false,
      requestSuceessFlag: false, // request 请求模型服务成功回调
      requestErrorFlag: false,
      hasParentCollection: false
    }
  },
  mounted () {
    EventBus.$on('sendCbBlock', (block) => {
      this.getBlockData()
    })
  },
  destroyed () {
    EventBus.$off('sendCbBlock')
  },
  watch: {
    'block': {
      handler () {
        this.getBlockData()
      },
      immediate: true
    }
  },
  methods: {
    getBlockData () {
      const blockId = this.block.id
      const rootBlock = this?.workspace?.getBlockById(blockId)
      const modalParentTypes = ['open_modal', 'close_modal']
      // const modalTypes = ['modal_close', 'modal_open'] // 回调所连接的input
      const parent = rootBlock.getParent()
      this.modalOpenFlag = false
      this.modalCloseFlag = false
      this.requestSuceessFlag = false
      this.requestErrorFlag = false
      this.hasParentCollection = !!parent
      const requestParentTypes = ['request_model', 'form_submit']
      // const requestTypes = ['success_func', 'error_func']
      if (parent && modalParentTypes.includes(parent.type)) {
        // 父级是弹窗
        const open = parent.getInputTargetBlock('modal_open')
        const close = parent.getInputTargetBlock('modal_close')
        this.modalOpenFlag = open?.id === blockId
        this.modalCloseFlag = close?.id === blockId
      } else if (parent && requestParentTypes.includes(parent.type)) {
        // 父级是数据请求 request
        const successCb = parent.getInputTargetBlock('success_func')
        const errorCb = parent.getInputTargetBlock('error_func')
        this.requestSuceessFlag = successCb?.id === blockId
        this.requestErrorFlag = errorCb?.id === blockId
      }

      if (this.requestSuceessFlag || this.requestErrorFlag) {
        this.setModelRequestCb()
      }
      if (this.modalOpenFlag || this.modalCloseFlag) {
        this.setModalCb()
      }
      // 获取右侧的参数列表
      this.paramList = []
      for (let i = 0; i < rootBlock.itemCount_; i++) {
        const input = rootBlock.getInput(`ADD${i}`)
        const value = input?.connection?.targetConnection?.sourceBlock_?.getFieldValue('CODE') || ''
        const insideBlock = rootBlock.getInputTargetBlock(`ADD${i}`)
        this.paramList.push({ value, editable: !value ? true : insideBlock?.isEditable() })
      }
    },
    // 添加事件参数
    addEventParam () {
      this.$refs.addParam.addForm({}, this.paramList.length)
    },
    editEventParam (param, index) {
      this.$refs.addParam.editForm({ param }, index)
    },
    handleAddParam (data) {
      this.paramList.push({ value: data.param, editable: true })
      const index = data.index || 0
      const rootBlock = this?.workspace?.getBlockById(this.block.id) // input
      rootBlock.itemCount_++
      rootBlock.updateShape_()
      var connection = rootBlock.getInput(`ADD${index}`).connection
      const newBlock = this.workspace.newBlock('params_input')
      newBlock.setFieldValue(data.param, 'CODE')
      connection.connect(newBlock.outputConnection)
      // rootBlock.initSvg()
      // rootBlock.updateShape_()
      this.updateWorkspaceWithXml()
    },
    handleEditParam (data) {
      const rootBlock = this?.workspace?.getBlockById(this.block.id)
      this.$set(this.paramList, data.index, { value: data.param })
      const index = data.index || 0
      const targetBlock = rootBlock.getInputTargetBlock(`ADD${index}`)
      // 如果积木被移除就没有targetBlock 需要手动加一个，有的话直接修改值
      if (!targetBlock) {
        const connection = rootBlock.getInput(`ADD${index}`).connection
        const newBlock = this.workspace.newBlock('params_input')
        newBlock.setFieldValue(data.param, 'CODE')
        connection.connect(newBlock.outputConnection)
        this.updateWorkspaceWithXml()
      } else {
        targetBlock.setFieldValue(data.param, 'CODE')
      }
    },

    // 移除参数
    removeParams (param, index) {
      this.paramList.splice(index, 1)
      const rootBlock = this?.workspace?.getBlockById(this.block.id)

      // // 移除input并将 对应input中的积木从workspace删除
      const insideContent = rootBlock.getInputTargetBlock(`ADD${index}`)
      insideContent && insideContent.dispose()
      rootBlock.removeInput(`ADD${index}`)

      const targetInsideBlocks = [] // 保存之前的连接块
      for (let i = index + 1; i < rootBlock.itemCount_; i++) {
        const targetBlock = rootBlock.getInputTargetBlock(`ADD${i}`)
        targetInsideBlocks.push(targetBlock)
        rootBlock.removeInput(`ADD${i}`)
      }
      rootBlock.itemCount_--
      rootBlock.updateShape_()
      for (let i = 0; i < targetInsideBlocks.length; i++) {
        var connection = rootBlock.getInput(`ADD${index + i}`).connection
        const targetBlock = targetInsideBlocks[i]
        connection.connect(targetBlock.outputConnection)
      }
    },
    // 参数能否编辑
    showEdit (index) {
      if (this.modalOpenFlag && index === 0) {
        return false
      } else if (this.modalCloseFlag && index < 2) {
        return false
      }
      return true
    },
    // 设置模态框打开关闭回调的参数
    setModalCb () {
      const rootBlock = this?.workspace?.getBlockById(this.block.id)
      if (!rootBlock.itemCount_) {
        this.handleAddParam({ param: 'tctx', index: 0, editable: false })
        if (this.modalCloseFlag) {
          this.handleAddParam({ param: 'args', index: 1, editable: false })
        }
      } else {
        if (this.modalCloseFlag && rootBlock.itemCount_ < 2) {
          rootBlock.itemCount_ = 2
          rootBlock.updateShape_()
        }
        for (let i = 0; i < rootBlock.itemCount_; i++) {
          const input = rootBlock.getInput(`ADD${i}`)
          if (i === 0) {
            const insideBlock = rootBlock.getInputTargetBlock('ADD0')
            if (!insideBlock) return
            if (insideBlock.type === 'params_input') {
              if (insideBlock.getFieldValue('CODE') !== 'tctx') {
                insideBlock.setFieldValue('tctx', 'CODE')
              }
            } else {
              const insideContent = rootBlock.getInputTargetBlock(`ADD${i}`)
              insideContent && insideContent.dispose()
              this.handleAddParam({ param: 'args', index: 1, editable: false })
            }
            insideBlock.setEditable(false)
            insideBlock.setDeletable(false)
            insideBlock.setMovable(false)
          } else if (i === 1 && this.modalCloseFlag) {
            let insideBlock = rootBlock.getInputTargetBlock('ADD1')
            if (!insideBlock) {
              var connection = rootBlock.getInput(`ADD1`).connection
              const newBlock = this.workspace.newBlock('params_input')
              newBlock.setFieldValue('args', 'CODE')
              connection.connect(newBlock.outputConnection)
              this.updateWorkspaceWithXml()
            } else if (insideBlock.type === 'params_input') {
              if (insideBlock.getFieldValue('CODE') !== 'args') {
                insideBlock.setFieldValue('args', 'CODE')
              }
            } else {
              const insideContent = rootBlock.getInputTargetBlock(`ADD${i}`)
              insideContent && insideContent.dispose()
              this.handleAddParam({ param: 'args', index: 1, editable: false })
            }
            insideBlock = rootBlock.getInputTargetBlock('ADD1')
            insideBlock.setEditable(false)
            insideBlock.setDeletable(false)
            insideBlock.setMovable(false)
          } else {
            const insideBlock = rootBlock.getInputTargetBlock(`ADD${i}`)
            if (!insideBlock) return
            insideBlock.setEditable(true)
            insideBlock.setEditable(true)
            insideBlock.setEditable(true)
          }
        }
      }
    },
    // 设置模型请求的回调的参数
    setModelRequestCb () {
      const rootBlock = this?.workspace?.getBlockById(this.block.id)
      if (!rootBlock.itemCount_) {
        if (this.requestSuceessFlag) {
          this.handleAddParam({ param: 'response', index: 0, editable: false })
        } else if (this.requestErrorFlag) {
          this.handleAddParam({ param: 'error', index: 0, editable: false })
        }
      } else {
        for (let i = 0; i < rootBlock.itemCount_; i++) {
          const input = rootBlock.getInput(`ADD${i}`)
          if (i === 0) {
            const insideBlock = rootBlock.getInputTargetBlock('ADD0')
            if (!insideBlock) {
              var connection = rootBlock.getInput(`ADD0`).connection
              const newBlock = this.workspace.newBlock('params_input')
              if (this.requestSuceessFlag) {
                newBlock.setFieldValue('response', 'CODE')
              } else if (this.requestErrorFlag) {
                newBlock.setFieldValue('error', 'CODE')
              }
              connection.connect(newBlock.outputConnection)
              this.updateWorkspaceWithXml()
            } else if (insideBlock.type === 'params_input') {
              if (this.requestSuceessFlag && insideBlock.getFieldValue('CODE') !== 'response') {
                insideBlock.setFieldValue('response', 'CODE')
              } else if (this.requestErrorFlag && insideBlock.getFieldValue('CODE') !== 'error') {
                insideBlock.setFieldValue('error', 'CODE')
              }
            } else {
              const insideContent = rootBlock.getInputTargetBlock(`ADD${i}`)
              insideContent && insideContent.dispose()
              this.handleAddParam({ param: 'args', index: 0, editable: false })
            }
            insideBlock.setEditable(false)
            insideBlock.setDeletable(false)
            insideBlock.setMovable(false)
          } else {
            const insideBlock = rootBlock.getInputTargetBlock(`ADD${i}`)
            if (!insideBlock) return
            insideBlock.setEditable(true)
            insideBlock.setEditable(true)
            insideBlock.setEditable(true)
          }
        }
      }
    },
    updateWorkspaceWithXml () {
      const xml = Blockly.Xml.workspaceToDom(this.workspace)
      Blockly.Xml.clearWorkspaceAndLoadFromXml(xml, this.workspace)
    }

  }
}
</script>

<style scoped>

</style>
